<template>
    <div class="admin-page">
        <div class="page-header">
            <div style="display: flex;">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">用户名:</span>
                        <el-input v-model="form.search" placeholder="用户名" size="small"
                                  style="width: 160px;"></el-input>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">身份:</span>
                        <el-select v-model="form.source" size="small" style="width: 110px;" placeholder="全部" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="普通用户" value="1"></el-option>
                            <el-option label="特殊用户" value="2"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">等级:</span>
                        <el-select v-model="form.is_up" size="small" style="width: 130px;" placeholder="全部" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="萌新" value="0"></el-option>
                            <el-option label="初级服务商" value="1"></el-option>
                            <el-option label="中级服务商" value="2"></el-option>
                            <el-option label="高级服务商" value="3"></el-option>
                            <el-option label="区域服务商" value="4"></el-option>
                            <el-option label="城市服务商" value="5"></el-option>
                            <el-option label="大区服务商" value="6"></el-option>
                            <el-option label="全球服务商" value="7"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">日期:</span>
                        <el-date-picker
                            size="small"
                            v-model="form.start_time"
                            type="date"
                            style="width: 150px;"
                            placeholder="开始日期">
                        </el-date-picker>
                        <span style="margin: 0 5px;">至</span>
                        <el-date-picker
                            size="small"
                            v-model="form.end_time"
                            type="date"
                            style="width: 150px;"
                            placeholder="结束日期">
                        </el-date-picker>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="small" @click="toSearch">搜索</el-button>
                    <el-button type="success" size="small" @click="reset">重置</el-button>
                </div>

            </div>
            <el-table height="560" :data="adminList" border style="width: 100%;overflow-y: auto;margin-top: 15px;"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="id" label="ID" width="80" align="center"/>
                <el-table-column label="用户名" width="100" align="center">
                    <template slot-scope="scope">
                        <span style="color: #66b1ff; cursor: pointer;" @click="handleUsernameClick(scope.row)">
                            {{ scope.row.username }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="nickname" label="用户昵称" align="center" width="100"/>
                <el-table-column prop="surplus_grain" label="余粮" align="center" width="100"/>
                <el-table-column prop="pid" label="推荐人" align="center" width="100"/>
                <!--                <el-table-column label="推荐人" width="120">
                                    <template slot-scope="scope">
                                        <span style="color: #66b1ff; cursor: pointer;" @click="openChangeTuiDialog(scope.row)"
                                              title="点击修改推荐人">
                                            {{ scope.row.pid || '-' }}
                                        </span>
                                    </template>
                                </el-table-column>-->
                <el-table-column prop="money" label="业绩" align="center" width="100"/>
                <el-table-column prop="up_init_money" label="购买金额" width="100" align="center"/>
                <el-table-column prop="g_pid" label="挂载人" align="center" width="120"/>
                <el-table-column prop="s_g_pid" label="实际挂载人" align="center" width="120"/>
                <!--                <el-table-column label="实际挂载人" width="120">
                                    <template slot-scope="scope">
                                        <span style="color: #66b1ff; cursor: pointer;" @click="openChangeGuaDialog(scope.row)"
                                              title="点击修改挂载人">
                                            {{ scope.row.s_g_pid }}
                                        </span>
                                    </template>
                                </el-table-column>-->
                <el-table-column prop="self_re_code" label="用户邀请码" align="center" width="100"/>
                <el-table-column prop="source" label="用户身份" align="center" width="80">

                    <template slot-scope="scope">
                        {{ scope.row.source === 1 ? '普通用户' : '特殊用户' }}
                    </template>
                </el-table-column>
                <el-table-column  align="center" label="用户码" width="100">
                    <template slot-scope="scope">
                        <div style=" text-align: center;">
                            <div @click="showQRCodeDialog(baseUrl + scope.row.self_re_code)">
                                <qrcode-vue :value="baseUrl + scope.row.self_re_code" :size="50" level="H"/>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="等级" width="100">
                    <template slot-scope="scope">
                        <span style="color: #66b1ff; cursor: pointer;" @click="handleUsernameClick1(scope.row)">
                            {{ scope.row.is_up }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="create_time" label="创建时间" align="center" width="150"/>
                <el-table-column label="操作" width="400">
                    <template slot-scope="scope">
                        <el-button type="success" size="small" @click="handleStateChange(scope.row)"
                                   :style="{ backgroundColor: scope.row.state === 0? 'red' : '#67c23a' }">
                            {{ scope.row.state === 0 ? '禁用' : '启用' }}
                        </el-button>
                        <el-button type="text" size="small" @click="toShowDialog(scope.row)">
                            直推树
                        </el-button>
                        <el-button type="text" size="small" @click="toShowDialog1(scope.row)">
                            挂点树
                        </el-button>
                        <el-button type="text" size="small" @click="toShowDialog2(scope.row)">
                            子节点
                        </el-button>
                        <el-button type="text" size="small" @click="toChangeTel(scope.row)">
                            修改手机号
                        </el-button>
                                                <el-button type="text" size="small" @click="toAddMoney(scope.row)">
                                                    充值
                                                </el-button>
                        <el-button type="text" size="small" @click="handleDeleteUser(scope.row)">
                            删除用户
                        </el-button>
<!--                                                <el-button type="text" size="small" @click="toChangeMoney(scope.row)">
                                                    修改金额
                                                </el-button>
                                                <el-button type="text" size="small" @click="toChangePassword(scope.row)">
                                                    修改密码
                                                </el-button>-->
                        <!--                        <el-button type="text" size="small" @click="toChangeRecord(scope.row)">-->
                        <!--                            变更记录-->
                        <!--                        </el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="15"
                layout="total, prev, pager, next, jumper"
                :total="total"
            />
        </div>
        <el-dialog
            title="服务商列表"
            :visible.sync="centerDialogVisible"
            width="30%"
            center>
            <div class="dialog-content" v-if="userServerList.length >0">
                <div class="info-row" v-for="(item,index) in userServerList" :key="index">
                    <span class="label">{{ item.is_up }}</span>
                    <span class="service-provider">{{ item.username}}</span>
                    <span class="label">业绩:</span>
                    <span class="performance">{{ item.money }}</span>
                </div>
            </div>
            <div v-else style="width: 100%;text-align: center">还没有服务商信息哦</div>
        </el-dialog>
        <el-dialog
            title="服务商列表"
            :visible.sync="centerDialogVisible1"
            width="20%"
            center>
            <div class="dialog-content">
                <div style="display: flex;align-items: center">
                    <div style="width: 30%;">用户ID:</div>
                    <el-input v-model="userId" size="small" disabled style="width: 70%;"></el-input>
                </div>
                <div style="display: flex;align-items: center;margin-top: 15px;">
                    <div style="width: 30%;">用户名:</div>
                    <el-input v-model="username" size="small" disabled style="width: 70%;"></el-input>
                </div>

                <div style="display: flex;align-items: center;margin-top: 15px;">
                    <div style="width: 30%;">用户等级:</div>
                    <el-select v-model="userLevel" size="small" style="width: 70%;">
                        <el-option label="初级服务商" value="1"></el-option>
                        <el-option label="中级服务商" value="2"></el-option>
                        <el-option label="高级服务商" value="3"></el-option>
                        <el-option label="区域服务商" value="4"></el-option>
                        <el-option label="城市服务商" value="5"></el-option>
                        <el-option label="大区服务商" value="6"></el-option>
                        <el-option label="全球服务商" value="7"></el-option>
                    </el-select>
                </div>

            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible1 = false" size="small">取消</el-button>
                <el-button type="primary" @click="submit" size="small">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog
            title="删除用户"
            :visible.sync="deleteUserDialogVisible"
            width="30%"
            center>
            <div v-if="deleteUserInfo">
                <div class="detail-item"><span class="detail-label">用户ID:</span><span class="detail-value">{{ deleteUserInfo.id }}</span></div>
                <div class="detail-item"><span class="detail-label">用户名:</span><span class="detail-value">{{ deleteUserInfo.username }}</span></div>
                <div class="detail-item"><span class="detail-label">等级:</span><span class="detail-value">{{ deleteUserInfo.is_up === '0' || deleteUserInfo.is_up === 0 ? '萌新' : deleteUserInfo.is_up }}</span></div>
                <div class="detail-item" style="color: #f56c6c; font-weight: bold;">确定要删除该用户吗？此操作不可恢复！</div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deleteUserDialogVisible = false" size="small">取消</el-button>
                <el-button type="danger" @click="confirmDeleteUser" size="small">确定删除</el-button>
            </div>
        </el-dialog>

        <!-- Render the AddMoney component, but don't control its visibility here -->
        <add-money ref="addMoneyDialog" @recharge-success="handleRechargeSuccess">
        </add-money>
        <change-money ref="addMoneyDialog" @recharge-success="handleRechargeSuccess">
        </change-money>

        <change-tel ref="changeTel" @recharge-success="handleRechargeSuccess">
        </change-tel>

        <!-- Add the change dialog components -->
        <change-tui ref="changeTuiDialog" @change-success="handleChangeSuccess"></change-tui>
        <change-gua ref="changeGuaDialog" @change-success="handleChangeSuccess"></change-gua>
        <change-password ref="changePasswordDialog" ></change-password>
        <change-record ref="changeRecord" ></change-record>

        <!-- Add the change dialog components -->
        <change-tui ref="changeTuiDialog" @change-success="handleChangeSuccess"></change-tui>
        <change-gua ref="changeGuaDialog" @change-success="handleChangeSuccess"></change-gua>
        <change-password ref="changePasswordDialog" ></change-password>
        <change-record ref="changeRecord" ></change-record>

        <el-dialog title="二维码" class="test" :visible.sync="qrCodeDialogVisible" width="300px" :close-on-click-modal="true">
            <div style="text-align: center;">
                <qrcode-vue :value="currentQRCode" :size="200" level="H"/>
            </div>
        </el-dialog>

    </div>
</template>

<script>

import AddMoney from './operate/addMoney.vue';
import ChangeTui from './operate/changeTui.vue';
import ChangeGua from './operate/changeGua.vue';
import ChangePassword from './operate/changePassword.vue';
import changeRecord from './record/changeRecord.vue';
import changeMoney from './operate/changeMoney.vue';
import changeTel from './operate/changeTel.vue';
import QrcodeVue from "qrcode.vue";
import {mapState} from "vuex";

export default {
    components: {
        QrcodeVue,
        AddMoney,
        ChangeTui,
        ChangeGua,
        ChangePassword,
        changeRecord,
        changeTel,
        changeMoney
    },
    computed: {
        ...mapState(["userInfo"]),
        qrcodeValue() {
            return this.baseUrl + (this.adminForm.content || '');
        }
    },
    data() {
        return {
            currentQRCode: '',
            adminList: [],
            deleteUserDialogVisible: false,
            qrCodeDialogVisible: false,
            currentPage: 1,
            pageSize: 15,
            total: 0,
            baseUrl: this.$appConfig.baseUrl +  'pagesAuth/public/login/index?source=1&re_code=',
            form: {
                search: "",
                source: "",
                is_up: "",
                state: "",
                start_time: "",
                end_time: ""
            },
            showDialog: false,
            showDialog1: false,
            userLevel: "",
            userId: "",
            username: "",
            centerDialogVisible: false,
            centerDialogVisible1: false,
            userServerList: [],
            searchParams: {},
        };
    },
    mounted() {
        this.fetchAdminList();
    },
    methods: {
        handleDeleteUser(row) {
            console.log(row)
            // 只允许萌新等级（0）
            if (row.is_up !== '萌新') {
                this.$message.warning('只有萌新等级的用户才能删除');
                return;
            }
            this.deleteUserInfo = row;
            this.deleteUserDialogVisible = true;
        },
        // 新增：删除用户确认
        confirmDeleteUser() {
            if (!this.deleteUserInfo) return;
            this.$http.post('/admin/User/delUser', { id: this.deleteUserInfo.id }).then(result => {
                if (result.code === 200) {
                    this.$message.success('删除成功');
                    this.deleteUserDialogVisible = false;
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '删除失败');
                }
            }).catch(() => {
                this.$message.error('删除失败');
            });
        },
        showQRCodeDialog(url) {
            this.currentQRCode = url;
            this.qrCodeDialogVisible = true;
        },
        submit() {
            this.$confirm('您确定要修改用户等级吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const datalist = {
                    user_id: this.userId,
                    is_up: this.userLevel,
                };
                this.$http.post('/admin/User/setUserIsUp', datalist).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.centerDialogVisible1 = false;
                        this.fetchAdminList();
                    } else {
                        this.$message.error(result.msg);
                    }
                }).catch(error => {
                    console.error('获取列表失败:', error);
                    this.$message.error('获取数据失败，请重试');
                });
            }).catch(() => {
                // 用户点击取消时的处理逻辑，这里可以不做任何处理
            });
        },
        handleUsernameClick1(row) {
            console.log(row)
            this.userLevel = row.is_up
            this.userId = row.id
            this.username = row.username
            this.centerDialogVisible1 = true
        },
        handleUsernameClick(e) {
            const user_id = e.id
            this.$http.get('/admin/User/getThreeChildrenInfo',{params:{user_id}}).then(result => {
                if (result.code === 200) {
                    this.userServerList = result.data
                    console.log(this.userServerList)
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                console.error('获取列表失败:', error);
                this.$message.error('获取数据失败，请重试');
            }).finally(() => {
                this.$message.closeAll();
            });
            this.centerDialogVisible = true
        },
        handleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            this.$http.post('/admin/User/del', {
                title: row.title,
                clas_id: row.clas_id,
                type: row.type,
                description: row.description,
                thumb: row.thumb,
                content: row.content,
                sort: row.sort,
                pur_price: row.pur_price,
                price: row.price,
                num: row.num,
                admin_id: row.admin_id,
                id: row.id,
                state: newState
            }).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },
        fetchAdminList(params = {}) {
            const mergedParams = {
                is_test:1,
                ...params,
                page: params.page || this.currentPage,
                limit: 15
            };

            this.$message.info({
                message: '正在加载数据...',
                duration: 0,
                showClose: true,
                iconClass: 'el-icon-loading'
            });
            this.$http.get('/admin/User/lists', {params: mergedParams}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                console.error('获取列表失败:', error);
                this.$message.error('获取数据失败，请重试');
            }).finally(() => {
                this.$message.closeAll();
            });
        },
        handleSizeChange(val) {
            this.pageSize = 15;
            this.fetchAdminList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList(this.searchParams);
        },
        toSearch() {
            const formatDate = (date) => {
                if (!date) return '';
                const d = new Date(date);
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                const seconds = String(d.getSeconds()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                const timestamp = new Date(formattedDate).getTime();
                return Math.floor(timestamp / 1000);
            };

            this.currentPage = 1;

            this.searchParams = {
                ...this.form,
                start_time: formatDate(this.form.start_time),
                end_time: formatDate(this.form.end_time),
            };

            Object.keys(this.searchParams).forEach(key => {
                if (this.searchParams[key] === '' || this.searchParams[key] === null) {
                    delete this.searchParams[key];
                }
            });

            this.fetchAdminList(this.searchParams);
        },
        reset() {
            this.form = {
                search: "",
                source: "",
                is_up: "",
                state: "",
                start_time: "",
                end_time: ""
            };
            this.searchParams = {};
            this.currentPage = 1;
            this.pageSize = 15;

            this.fetchAdminList({
                page: 1,
                limit: 15,
                per_page: 15,
                pageSize: 15
            });
        },
        toShowDialog(e) {
            this.$router.push({path: "allDate/zhi", query: {id: e.id, type: 1}})
        },
        toShowDialog1(e) {
            this.$router.push({path: "allDate/gua", query: {id: e.id, type: 2}})
        },
        toShowDialog2(e) {
            this.$router.push({path: "allDate/detail", query: {id: e.id, type: 2}})
        },
        toAddMoney(row) {
            this.$refs.addMoneyDialog.openDialog(row);
        },
        toChangeTel(row) {
            this.$refs.changeTel.openDialog(row);
        },
        toChangeMoney(row) {
            this.$refs.addMoneyDialog.openDialog(row);
        },
        toChangePassword(row) {
            this.$refs.changePasswordDialog.openDialog(row);
        },
        toChangeRecord(row) {
            this.$refs.changeRecord.openDialog(row);
        },
        // Handler for successful recharge event from AddMoney
        handleRechargeSuccess() {
            // Dialog closing is handled by the child now
            // We just need to refresh the list
            this.fetchAdminList();
        },
        // Methods to open the change dialogs
        openChangeTuiDialog(userData) {
            this.$refs.changeTuiDialog.openDialog(userData);
        },
        openChangeGuaDialog(userData) {
            this.$refs.changeGuaDialog.openDialog(userData);
        },
        // Handler for successful changes from either dialog
        handleChangeSuccess() {
            this.fetchAdminList(); // Refresh the user list
        },
    }
};
</script>
<style lang="less" scoped>

.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #f0f2f5;
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    .table-header {
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
        }

        .table-actions {
            .el-button {
                margin-left: 12px;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }
}

.el-dialog {
    border-radius: 12px;
    overflow: hidden;
    max-height: 90vh;
    display: flex;
    flex-direction: column;

    :deep(.el-dialog__header) {
        padding: 20px 24px !important;
        border-bottom: 1px solid #f0f2f5;
        margin: 0;

        .el-dialog__title {
            font-size: 18px;
            font-weight: 600;
            color: #1f2937;
        }
    }

    :deep(.el-dialog__body) {
        padding: 32px 24px;
        flex: 1;
        overflow-y: auto;

        .el-form-item {
            .el-input,
            .el-select {
                width: 320px;
            }
        }
    }

    :deep(.el-tree) {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
        padding: 10px;
    }

    :deep(.el-dialog__footer) {
        padding: 16px 24px;
        border-top: 1px solid #f0f2f5;
    }

    :deep(.el-form-item__label) {
        font-weight: 500;
        color: #374151;
    }

    :deep(.el-button) {
        padding: 8px 20px;
        transition: all 0.3s;

        &:hover {
            transform: translateY(-1px);
        }
    }
}

.dialog-content {
    padding: 10px;
}

.info-row {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 10px;
}

.label {
    width: 80px;
    text-align: right;
    line-height: 36px;
    color: #666;
}

.service-provider,
.performance {
    line-height: 36px;
    background-color: #f4f4f4;
    padding: 0 10px;
    border-radius: 4px;
}

.search-item {
    margin-right: 10px;
}

.search-label {
    margin-right: 5px;
    white-space: nowrap;
    font-size: 14px;
    color: #606266;
    //min-width: 60px;
    text-align: right;
}

/deep/ .el-dialog__header {
    padding: 10px !important;
}
</style>
